package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.base.BaseCanPlayActivity;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.beans.FCollect;
import com.sctvcloud.dongqu.beans.FComment;
import com.sctvcloud.dongqu.beans.FTopic;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.Titles;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.TopicDeatilAdapter;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.utils.CollectionUtils;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;
import com.sctvcloud.dongqu.ui.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sctvcloud.dongqu.R.id.comment_layout_number;

/**
 * 专题详情
 */
public class TopicDetailActivity1 extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener,
        CanRefreshLayout.IScrollView {
    @BindView(R.id.topic_detail_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.topic_newes_list)
    protected RecyclerView topic_list;
    @BindView(R.id.comment_layout_write_comment)
    protected CustomFontTextView comment_ct;
    @BindView(comment_layout_number)
    protected CustomFontTextView comment_number;
    @BindView(R.id.comment_layout_collection)
    protected CustomFontTextView mBtnCollect;
    @BindView(R.id.title_top_layout_edit)
    protected CustomFontTextView share;
    private LinearLayoutManager manager;
    private TopicDeatilAdapter adapter;
    private boolean isCollected = false;
    private String topImage = "";
    private String topTitle = "";
    private String specialId;
    private String sharedUrl;
    private ArrayList<NewsItem> subSpecialList;
    private int commentNumber;
    public static int REQUEST_COMMENT_TOPIC_CODE = 404;
    private FTopic topic;
    private List<NewsItem> newsItems;
    private FCollect mFCollect;
    private int capacity = 5;//请求数据条数
    private int indexNumber = 0;
    private String baseConstUrl;
    private String news24Domain = "";//市州新闻静态请求路径的域名
    private boolean isCityState = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        isCityState = getIntent().getBooleanExtra(Constances.IS_CITY_STATE, false);
        baseUrl = getIntent().getStringExtra(EX_URL);
        if (isCityState) {
            //泸州新闻动态接口域名
            baseConstUrl = Cache.getInstance().getChoosedCityStUrl();//Constances.LZ_BASE_URL;
            String news24Url = Cache.getInstance().getChoosedCityNewsUrl();
            news24Domain = UIUtils.getDomain(news24Url);
            share.setVisibility(View.GONE);
        } else {
            news24Domain = "";
        }
        if (TextUtils.isEmpty(baseUrl)) {
            toast(R.string.loading_invalid_data);
            finish();
            return;
        }
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_topic_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onCollectCheckResult(int result) {
        setBtnCollectStyle(result > 0);
    }

    private void initView() {


        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        topic_list.setItemAnimator(new DefaultItemAnimator());
        topic_list.setLayoutManager(manager);
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();
    }

    @OnClick({R.id.title_top_back, R.id.title_top_layout_edit, R.id.comment_layout_collection, R.id.comment_layout_share})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                finish();
                break;
            case R.id.title_top_layout_edit:
                if (topic != null && !TextUtils.isEmpty(topic.getSharedUrl())) {
                    this.setNewsId( topic.getSpecialId());
                    showShareFragment(topic, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pairs) {

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }

                break;
            case R.id.comment_layout_collection:
                doCollect();
                break;
            case R.id.comment_layout_share:
                if (topic != null && !TextUtils.isEmpty(topic.getSharedUrl())) {
                    this.setNewsId( topic.getSpecialId());
                    showShareFragment(topic, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pairs) {

                        }
                    });
                }
                break;
        }
    }

    @OnClick(comment_layout_number)
    public void commentClick(View view) {
        if (commentNumber != 0) {
            Intent intent = new Intent(this, CommentActivity.class);
            if (TextUtils.isEmpty(specialId)) {
                if (refreshLayout.isRefreshing()) {
                    toast("正在加载数据");
                } else {
                    toast(R.string.data_wrong);
                }
                return;
            }
            intent.putExtra(EX_ID, specialId);
            if (isCityState) {
                intent.putExtra(Constances.IS_CITY_STATE, true);
            }
            intent.putExtra(EX_TYPE_NEWS, Constances.REQUEST_COMMENT_TYPE_TOPIC);
            intent.putExtra(EX_COMMENT_TYPE, Constances.COMMENT_TYPE_TOPIC);
            startActivityForResult(intent, REQUEST_COMMENT_TOPIC_CODE);
        }
    }


    @OnClick(R.id.comment_layout_write_comment)
    public void writeComment(View view) {
        if (TextUtils.isEmpty(specialId)) {
            if (refreshLayout.isRefreshing()) {
                toast("数据正在加载");
            } else {
                toast(R.string.data_wrong);
            }
            return;
        }
        if (TextUtils.isEmpty(baseConstUrl)) {
            showCommentDialog(specialId, null, Constances.COMMENT_TYPE_TOPIC);  //2代表专题评论
        } else {
            showCommentDialog(specialId, true, null, Constances.COMMENT_TYPE_TOPIC);  //2代表专题评论
        }

    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {
        getNewsList();
    }

    private void getNewsList() {
        JLog.e("=====url=-==" + baseUrl);
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), baseUrl, new AbsListNetCallback<NewsItem>(NewsItem.class) {
            @Override
            public void onSuc(List<NewsItem> datas) {
                newsItems = datas;
                topImage = news24Domain + getPageResponse().getData().getTopImage();
                topTitle = getPageResponse().getData().getTopTitle();
                specialId = getPageResponse().getData().getSpecialId();
                sharedUrl = news24Domain + getPageResponse().getData().getSharedUrl();
                subSpecialList = getPageResponse().getData().getSubSpecialList();
                if (ListUtils.isListValued(subSpecialList)) {
                    for (NewsItem item : subSpecialList) {
                        item.setSubTopic(true);
                    }
                    newsItems.addAll(0, subSpecialList);
                }
                if (ListUtils.isListValued(newsItems) && isCityState) {
                    for (int i = 0; i < newsItems.size(); i++) {
                        newsItems.get(i).setNewsUrl(news24Domain + newsItems.get(i).getNewsUrl());
                        newsItems.get(i).setNewsImage(news24Domain + newsItems.get(i).getNewsImage());
                    }
                }
                checkCollect(specialId);
                if (ListUtils.isListValued(datas)) {
                    setData(null);
                }
                //获取评论数据
                getNewestCommentList(specialId);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                getNewestCommentList(specialId);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    /**
     * 获取评论数据
     *
     * @param topicId 专题ID
     */
    private void getNewestCommentList(String topicId) {
        if (!TextUtils.isEmpty(topicId)) {
            //回到父类中进行评论数据的请求，最后返回当前页面做显示
            if (TextUtils.isEmpty(baseConstUrl)) {
                getCommentNews(topicId, Constances.REQUEST_COMMENT_TYPE_TOPIC, capacity, indexNumber);
            } else {
                getCommentNews(topicId, baseConstUrl + "/", Constances.REQUEST_COMMENT_TYPE_TOPIC, capacity, indexNumber);
            }
        }
    }

    /**
     * 处理评论数据
     *
     * @param datas
     * @return
     */
    private List<FComment> dataHandle(List<FComment> datas) {
        List<FComment> comments = new ArrayList<>();
        List<FComment> answers = new ArrayList<>();
        if (null != datas) {
            FComment comment;
            for (int i = 0; i < datas.size(); i++) {
                comment = datas.get(i);
                if (TextUtils.isEmpty(comment.getAnswerTo())) {
                    if (comments.size() < 5) {
                        comments.add(comment);
                    }
                } else {
                    answers.add(comment);
                }
            }

            for (int j = 0; j < answers.size(); j++) {
                FComment co = answers.get(j);
                for (int k = 0; k < comments.size(); k++) {
                    if (!TextUtils.isEmpty(co.getAnswerToCommentId()) && co.getAnswerToCommentId().equalsIgnoreCase(comments.get(k).getCommentId())) {
                        comments.add(k + 1, co);
                        break;
                    }
                }
            }
        }
        return comments;

    }

    private void setData(List<FComment> commentList) {
        List<FComment> tempList = dataHandle(commentList);
        List<IListShowData> list = new ArrayList<>();
        topic = new FTopic();
        if (!TextUtils.isEmpty(topImage) || !TextUtils.isEmpty(topTitle)) {
            String imgUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, topImage);
            topic.setSpecialId(specialId);
            topic.setTopImage(imgUrl);
            topic.setTopTitle(topTitle);
            topic.setSharedUrl(sharedUrl);
            topic.setViewType(TopicDeatilAdapter.VIEWTYPE_TOP);
            list.add(topic);
        }
        if (ListUtils.isListValued(newsItems)) {
            for (int i = 0; i < newsItems.size(); i++) {
                NewsItem newsItem = newsItems.get(i);
                if (newsItem.isSubTopic()) {
                    newsItem.setViewType(TopicDeatilAdapter.VIEWTYPE_SUB_TOPIC);
                } else {
                    newsItem.setViewType(TopicDeatilAdapter.VIEWTYPE_VIDEO);
                }
                newsItem.setLastItem(i == newsItems.size() - 1);
            }
            list.addAll(newsItems);
        }
        if (ListUtils.isListValued(tempList)) {
            Titles title = new Titles();
            title.setViewType(TopicDeatilAdapter.VIEWTYPE_TITLE);
            title.setDateString(getString(R.string.newes_latest_comment));
            list.add(title);
//            if (commentList.size() > 5) {
//                for (int i = 0; i < 5; i++) {
//                    commentList.get(i).setViewType(TopicDeatilAdapter.VIEWTYPE_COMMENT);
//                    list.add(commentList.get(i));
//                }
//            } else {
            for (FComment comment : tempList) {
                comment.setViewType(TopicDeatilAdapter.VIEWTYPE_COMMENT);
            }
            list.addAll(tempList);
//            }
        }

        if (adapter == null) {
            adapter = new TopicDeatilAdapter(this, list);
            adapter.setItemInternalClick(replyItemClick);
            // topic_list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
            topic_list.setAdapter(adapter);
        } else {
            adapter.setData(list);
        }
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
    }

    OnItemInternalClick replyItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FComment comment = (FComment) adapter.getItem(position);
            if (!TextUtils.isEmpty(comment.getCommentId())) {
                if (TextUtils.isEmpty(baseConstUrl)) {
                    showCommentDialog(specialId, comment.getCommentId(), Constances.COMMENT_TYPE_TOPIC);
                } else {
                    showCommentDialog(specialId, true, comment.getCommentId(), Constances.COMMENT_TYPE_TOPIC);
                }
            } else {
                toast("评论id为空");
            }

        }
    };

    private boolean initCollectData() {
        if (topic == null) {
            return false;
        }
        if (mFCollect == null) {
            mFCollect = new FCollect();
            mFCollect.setId(topic.getSpecialId());
            mFCollect.setUrl(baseUrl);
            mFCollect.setTitle(topic.getTopTitle());
            mFCollect.setImg(topic.getTopImage());
            mFCollect.setTime(topic.getPubTime());
            mFCollect.setDataType(4);
            mFCollect.setNewsMediaLength(topic.getNewsMediaLength());
            mFCollect.setLable(topic.getLable());
            mFCollect.setSharedUrl(topic.getSharedUrl());
            mFCollect.setViews(topic.getReadCount());
        }
        return true;
    }

    private void setBtnCollectStyle(boolean isCollected) {
        this.isCollected = isCollected;
        mBtnCollect.setText(isCollected ? R.string.mine_collection_succ : R.string.newes_collection);
        mBtnCollect.setTextColor(ContextCompat.getColor(this, isCollected ? R.color.white : R.color.colorFontSelect));
        mBtnCollect.setBackgroundResource(isCollected ? R.drawable.bg_red_ra : R.drawable.bg_look_back);
    }

    private void doCollect() {
        if (!initCollectData()) {
            toast(R.string.data_wrong);
            return;
        }
        if (isCollected) {
            CollectionUtils.getInstance().removeCollection(mFCollect.getId());
            setBtnCollectStyle(false);
            toast(R.string.mine_collection_removed_toast);
        } else {
            CollectionUtils.getInstance().addCollection(mFCollect);
            setBtnCollectStyle(true);
            toast(R.string.mine_collection_succ_toast);
        }
    }

    @Override
    protected void onCommentGetListSuc(int count, List<FComment> commentList) {
        super.onCommentGetListSuc(count, commentList);
        //获取评论数据，回调显示
        if (indexNumber >= count || count <= capacity) {
            commentNumber = count;
            refreshBottomCommentShowing(count);
            setData(commentList);
        } else {
            requestAll(count);
        }
    }

    /**
     * 获取全部数据
     *
     * @param ca
     */
    private void requestAll(int ca) {
        capacity = ca;
        indexNumber = 0;
        if (TextUtils.isEmpty(baseConstUrl)) {
            getCommentNews(specialId, Constances.REQUEST_COMMENT_TYPE_TOPIC, capacity, indexNumber);
        } else {
            getCommentNews(specialId, baseConstUrl + "/", Constances.REQUEST_COMMENT_TYPE_TOPIC, capacity, indexNumber);
        }
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
        if (TextUtils.isEmpty(baseConstUrl)) {
            getCommentNews(specialId, Constances.REQUEST_COMMENT_TYPE_TOPIC, capacity, indexNumber);
        } else {
            getCommentNews(specialId, baseConstUrl + "/", Constances.REQUEST_COMMENT_TYPE_TOPIC, capacity, indexNumber);
        }
    }

    private void refreshBottomCommentShowing(int count) {
        String str = getString(R.string.detail_comment_no);
        //  if (commentColumn != null && count > 0) {
        if (count > 0) {
            if (count > 99) {
                str = getString(R.string.detail_comment_counts);
            } else {
                str = getString(R.string.detail_comment_count, count);
            }
        }
        comment_number.setText(str);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_COMMENT_TOPIC_CODE) {
            //getCommentNews(specialId, 2, 5, 0);
            onRefresh();
        }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(topic_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(topic_list, 1);
    }
}
